<?php
/**
 * Patient Main Screen
 * 
 * In this screen, you can change patient master data and 
 * add monitoring monitorings
 * 
 */

use Nawa\MedicalStudy\MedicalCenter\Patient;
use Fox\Html\Button;
use Fox\Html\Input;
use Fox\Html\Block;
use Fox\Generator;
use Fox\Html\Screen;

// Initialize
$xview = Xview::instance();
$msid = $xview->val('msid');
$mcid = $xview->val('mcid');
$patientid = $xview->val('patientid');
$keys = array('msid' => $msid,'mcid' => $mcid);
$language = $xview->language();
/* @var $ms Nawa\MedicalStudy */
$ms = $xview->component('medicalstudies','object',$keys);
$mcPartner = $xview->component('medicalstudies','medicalcenter',$keys);
$medicalCenter = $mcPartner->medicalCenter();

// Load Patient Data
/* @var $patient Nawa\MedicalStudy\MedicalCenter\Patient */
$patient = $mcPartner->findPatients($msid.':'.$mcid.':'.$patientid);
if(!$patient->exists()) {
	$xview->accessDenied(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::ACCESS_DENIED),
						Generator::url('medicalstudies','medicalcenter',null,$keys));
}
// Patient Data
$validatedMonitorings = $monitorings = array();
$data = $patient->getData();
foreach($patient->monitorings() as $monitoring) {
	$monitoringData = $monitoring->getData();
	$monitorings[$monitoring->itemid][$monitoring->monitoringid] = $monitoringData;
	if($monitoringData['validated']) {
		$validatedMonitorings[$monitoring->itemid] = true;
	}
}
// Patient Visits
$visits = array();
foreach($patient->visits() as $visit) {
	$visits[$visit->itemid] = $visit->getData();
}
// Bread Crumb
$crumbs = $xview
	->component('medicalstudies','breadcrumb',
	array('deepness' => 5,
		  'customerid' => $ms->customer()->getId(),
		  'customer_name' => $ms->customer()->name1,
		  'msReference' => $ms->reference,
		  'msid' => $ms->getId(),
		  'msCenterCount' => $ms->countMedicalCentersPartners(),
		  'mcid' => $mcid,
		  'mcLabel' => $medicalCenter->label(),
		  'mcPatientCount' => $mcPartner->countPatients(),
		  'patient' => $patient,
		  'type' => Patient::BREADCRUMB_NODE
	)
);
$screen = new Screen('sPatient','update');
$screen->buttons('update')->color(Button::COLOR_BLUE);
$screen->breadcrumb()->crumbs($crumbs);

// Patient Master Data
$blHeader = $xview->component('medicalstudies','patientBlock',array('inline' => true));
$screen->add($blHeader);


// Monitoring List
$oneMonitoringBlockIsOpen = false;
foreach($ms->followup() as $followup) {
	$itemid = $followup->itemid;
	$followupLabels[$itemid] = $followup->label();
	$monitoringGridModel = $xview->component('medicalstudies','monitorings',array(
		'msid'		=> $msid,
		'mcid'		=> $mcid,
		'patientid' => $patient->patientid,
		'itemid' => $itemid
	));
	$blMonitoring = new Block('bMonitorings_'.$itemid,$followup->label());
	$visitInputs[$itemid] = $blMonitoring->add(new Input(array('visit_date','visit_date_'.$itemid)));
	$blMonitoring->collapsed(false);
	if(!empty($visits[$itemid])) {
		$visitData = array();
		foreach($visits[$itemid] as $field => $value) {
			$visitData[$field.'_'.$itemid] = $value;
		}
		$blMonitoring->initialize($visitData);
	//	$blMonitoring->item('visit_date_'.$itemid)->mandatory();
	}
	$monitoringGrid = clone $monitoringGridModel;
	$monitoringGrid->id('gMonitorings_'.$patient->patientid.'_'.$itemid);
	if(!empty($monitorings[$itemid])) {
		$oneMonitoringBlockIsOpen = true;
		$monitoringGrid->initialize($monitorings[$itemid],true);
		if(!empty($validatedMonitorings[$itemid])) {
			$monitoringGrid->footer()->remove('adnew');
		}
	} else {
		if($oneMonitoringBlockIsOpen) {
			$blMonitoring->collapsed(true);
		} 
	}
	
	$blMonitoring->add($monitoringGrid);
	$screen->add($blMonitoring);
}
$screen->initialize($data);
if($screen->submitted()) {
	$fields = $screen->get();
	if(!$screen->errors()) {
		try {
			$updated = false;
			$patient->setFields($fields);
			if(isset($visitInputs)) {
				foreach($visitInputs as $itemid => $input) {
					$visit_date = $input->get();
					$visit = $patient->findVisits($msid.':'.$mcid.':'.$patientid.':'.$itemid);
					if($visit->exists()) {
						$visit->setFields(array('visit_date' => $visit_date));
						$patient->replaceVisits($visit);
					} elseif(!empty($visit_date)) {
						$visit->setFields(array(
							'msid' => $msid,
							'mcid' => $mcid,
							'patientid' => $patientid,
							'itemid' => $itemid,
							'visit_date' => $visit_date
						));
						$patient->replaceVisits($visit);
					}
					if(!empty($monitorings[$itemid]) && empty($visit_date)) {
						throw new Exception(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::VISIT_DATE_MANDATORY,$followupLabels[$itemid]));
					}
				}
			}
			if($patient->update()) {
				$updated = true;
			}
			if($updated) {
			
				Fox\Message::Success(Msg(Nawa\Messages::BUNDLE,
									Nawa\Messages::PATIENT_UPDATED,
									$fields['reference']));
			//	$screen->redirect();
			}
			
		} catch(Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		} catch(\Exception $e) {
			Fox\Message::Error($e);
		}
	}
}
echo $screen->display();